PlayerManager = {};
local this = PlayerManager;

local gameObject;
local transform;
local speed = 20;
local bulletSpeed = 30;

local maxX;
local maxY;

local hp = 100;

local bulletPrefab;
local firePoints = {};

function PlayerManager.New()
	
	resMgr:LoadPrefab("Player", {"PlayerCon"}, this.OnLoadOK);
	PlayerManager.BulletOnLoadOK();
	
end

function PlayerManager.InitData()
	local screenMax = Camera.main:ScreenToWorldPoint(Vector3(Screen.width, Screen.height));
	local boradHalf = gameObject:GetComponent("SpriteRenderer").bounds.extents;
	maxX = screenMax.x - boradHalf.x;
	maxY = screenMax.y - boradHalf.y;
end

function PlayerManager.BulletOnLoadOK(objs)
	for i = 1, 2 do
		local name = "FirePoint" .. i;
		table.insert(firePoints, transform:Find(name));
	end
end

function PlayerManager.OnLoadOK(objs)
	gameObject = newObject(objs[0]);
	
	transform = gameObject.transform;
	transform.position = Vector3(0, - 4.05, - 1.5);
	
	local luaTrigger = gameObject:AddComponent(typeof(LuaTrigger2D));
	luaTrigger:SetEnterFunc(this.OnTriggerEnter, nil);
	
	this.InitData();
	
	UpdateBeat:Add(this.Update);
end

function PlayerManager.Update()
	this.Move();
	this.Fire();
	
end
local lastFireTime = 0;
function PlayerManager.Fire()
	if(Time.time - lastFireTime > 0.1) then
		
		lastFireTime = Time.time;
		
		for i, point in ipairs(firePoints) do
			-- local go = newObject(bulletPrefab);
			local go = poolMgr:Get("PlayerBullet");
			go.transform.position = point.position;
			go.transform.rotation = point.rotation;
			
			local body = go:GetComponent('Rigidbody2D');
			body.velocity = point.up * bulletSpeed;
			
		end
	end
end

function PlayerManager.Move()
	-- local dx=Input.GetAxis("Horizontal");
	-- local dy=Input.GetAxis("Vertical");
	-- local dir = Vector3.up*dy+Vector3.right*dx;
	-- transform:Translate(dir*Time.deltaTime*speed);
	if(Input.GetMouseButton(0)) then
		local pos = Camera.main:ScreenToWorldPoint(Input.mousePosition);
		pos.z = - 1.5;
		pos.x = Mathf.Clamp(pos.x, - maxX, maxX);
		pos.y = Mathf.Clamp(pos.y, - maxY, maxY);
		
		local vec = pos - transform.position;
		if(Vector3.SqrMagnitude(vec) < 0.5) then
			transform.position = pos;
		else
			local dir = Vector3.Normalize(vec);
			transform:Translate(dir * speed * Time.deltaTime);
		end
	end
end

function PlayerManager.OnTriggerEnter(collision)
	
	if(collision:CompareTag('EnemyBullet') or collision:CompareTag('Enemy')) then
		hp = hp - 1;
		poolMgr:Release("EnemyBullet",collision.gameObject);

		log("<color=red>hp:" .. hp .. "</color>");
		Event.Brocast("HpChange", hp);
		if(hp <= 0) then
			logWarn("你死亡了");
			UpdateBeat:Remove(this.Update);
			gameObject:SetActive(false);
		end
	end
end 